<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>移动端导航栏</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="./css/nav2.css">
</head>
<body>
<nav>
  <div class="menu-item">
    <a href="javascript:void(0)" class="menu-btn-icon btn-icon-close"></a>
    <!--    <a href="javascript:void(0)" class="menu-btn-font btn-font-menu"></a>-->
    <div class="clearfix"></div>
  </div>
  <ul class="nav-container-list">
    <li class="nav-list-item"><a href="">Item1</a></li>
    <li class="nav-list-item">
      <a href="">Item2</a>
      <ul class="nav-submenu-list">
        <li class="nav-submenu-item"><a href="">SubItem1</a></li>
        <li class="nav-submenu-item"><a href="">SubItem2</a></li>
        <li class="nav-submenu-item"><a href="">SubItem3</a></li>
        <li class="nav-submenu-item"><a href="">SubItem4</a></li>
      </ul>
    </li>
    <li class="nav-list-item"><a href="">Item3</a></li>
    <li class="nav-list-item"><a href="">Item4</a></li>
  </ul>
</nav>

<script>
  var btn = document.querySelector('.menu-btn-icon')
  var menu = document.querySelector('.nav-container-list')
  var menuIsCollapse = false;

  btn.onclick = function () {
    menuIsCollapse = !menuIsCollapse;
    if (menuIsCollapse) {//关闭按钮
      menu.style.display = 'none';
      btn.classList.remove('btn-icon-close')
      btn.classList.add('btn-icon-menu')
    } else {
      menu.style.display = 'block';
      btn.classList.remove('btn-icon-menu')
      btn.classList.add('btn-icon-close')

    }
  }


  /*方法一*/
  /*var mql = window.matchMedia("(min-width:480px)");
   mql.addListener(mediaChangeHandle)
   mediaChangeHandle(mql)

   function mediaChangeHandle(mql){
     //匹配成功，导航栏宽度大于480px
     //则无论如何也显示导航栏
     if(mql.matches){
       menu.style.display='block';
     }else{
       if(menuIsCollapse){
         menu.style.display='none';
       }else{
         menu.style.display='';
       }
     }
   }*/

  /*方法二*/
  window.addEventListener('resize', function () {
    var innerWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    mediaChangeHandle(
      innerWidth >= 480 ? {matches: true} : {matches: false}
    )
  }, false)

  function mediaChangeHandle(mql) {
    //匹配成功，导航栏宽度大于480px
    //则无论如何也显示导航栏
    if (mql.matches) {
      menu.style.display = 'block';
    } else {
      if (menuIsCollapse) {
        menu.style.display = 'none';
      } else {
        menu.style.display = '';
      }
    }
  }

</script>

</body>
</html>
